package org.ainlolcat.ctp.module.impl;

import org.ainlolcat.ctp.guice.Loader;
import org.ainlolcat.ctp.model.configuration.Configuration;
import org.ainlolcat.ctp.model.configuration.ModuleDef;
import org.ainlolcat.ctp.module.Container;
import org.ainlolcat.ctp.module.Module;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Created by IntelliJ IDEA.
 * User: ain
 * Date: 05.09.12
 * Time: 14:46
 * To change this template use File | Settings | File Templates.
 */
public class ContainerImpl implements Container {
    private static Logger log = Logger.getLogger(ContainerImpl.class.getName());

    private Configuration configuration;
    private List<Module> modules = new ArrayList<Module>();
    private Map<String, List<Module>> modules4source = new Hashtable<String, List<Module>>();
    private List<Module> dataSources;

    public Configuration getConfiguration() {
        return configuration;
    }

    public void setConfiguration(Configuration configuration) {
        this.configuration = configuration;
        for (ModuleDef md: configuration.getAllModules()){
            try{
                Module  m = (Module) Loader.get(Class.forName(md.getClazz()));
                m.setModuleDefinition(md);
            }catch (Exception e){
                log.log(Level.WARNING, "Cannot create module instance", e);
            }
        }
    }

    public List<Module> getSubscribers(String source){
        if (!modules4source.containsKey(source)) {
            List<Module> newGroup = new ArrayList<Module>();
            for (Module m : modules){
                if (m.getSources().contains(source)) newGroup.add(m);
            }
            modules4source.put(source, newGroup);
        }
        return modules4source.get(source);
    }

    public List<Module> getDataSources(){
        if (dataSources != null && !dataSources.isEmpty()) return dataSources;
        List<Module> temp = new ArrayList<Module>();
        for (Module m : modules){
            if (m.getSources() == null || m.getSources().isEmpty()) temp.add(m);
        }
        dataSources = temp;
        return dataSources;
    }
}
